package cn.com.yang.es;
/**
 * 构建查询条件
 * TODO
 * @author yangyijin
 * @since 2024年1月19日-上午9:00:03
 */

import java.util.List;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.DisMaxQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder.Type;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import cn.com.yang.utils.PinyinUtils;
import cn.com.yang.utils.StringUtils;
/**
 * 
 * TODO
 * @author yangyijin
 * @since 2024年1月19日-上午10:02:11
 */
public class EsUtil {
	
	/**
	 * 构建查询对象
	 * @param keyword 关键词
	 * @param fp 全拼
	 * @param sp 简拼
	 * @return 查询对象
	 */
	public static BoolQueryBuilder buildBooleanQueryBuilder(String keyword,String[] iks,String[] fps,String[] sps) {
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
//		queryBuilder.boost(5);//权重会影响结果排序
//		queryBuilder.must(QueryBuilders.termQuery("field", "value")).boost(5);
		DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
		boolean isZH = PinyinUtils.isAllChinese(keyword);
		if(isZH) {
			disMaxQueryBuilder.add(QueryBuilders.multiMatchQuery(keyword, iks).type(Type.BEST_FIELDS));
			String wildCard  =String.format("%s", keyword);
			for(String ik : iks) {
				disMaxQueryBuilder.add(QueryBuilders.wildcardQuery(wildCard, ik));
			}
		}else {
			//全拼
			String fullChars = PinyinUtils.toFullChars(keyword);
			disMaxQueryBuilder.add(QueryBuilders.multiMatchQuery(fullChars, fps).type(Type.BEST_FIELDS));
			//首字母
			String firstChars = PinyinUtils.toFirstChars(keyword);
			disMaxQueryBuilder.add(QueryBuilders.multiMatchQuery(firstChars, sps).type(Type.BEST_FIELDS));
		}
		queryBuilder.must(disMaxQueryBuilder);
		return queryBuilder;
	}
	/**
	 * 构建高亮查询对象
	 * @param fields
	 * such as:<br>
	 * <br>new ArrayList(){["name.fpy","","1","200"],["name.fpy","unified","1","200"]}
	 * <br>[0]=field name,
	 * <br>[1]=高亮器类型：fvh,plain,posting,unified,默认fvh
	 * <br>[2]=numOfFragments,default 5 if 0 equals fragment_size ignore
	 * <br>[3]=fragmentOffset,
	 * @return
	 */
	public static HighlightBuilder buHighlightBuilder(List<String[]> fields) {
		HighlightBuilder highlightBuilder = new HighlightBuilder();
		for(String[] field: fields) {
			HighlightBuilder.Field buildField = new HighlightBuilder.Field(field[0]);
			if(StringUtils.isNotBlank(field[1])) {
				buildField.highlighterType(field[1]);
			}
			if(StringUtils.isNotBlank(field[2])) {
				buildField.numOfFragments(Integer.valueOf(field[2]));
			}
			if(StringUtils.isNotBlank(field[3])) {
				buildField.fragmentOffset(Integer.valueOf(field[3]));
			}
			buildField.preTags("<font style='color:red'>");
			buildField.postTags("</font>");
			highlightBuilder.field(buildField);
		}
		return highlightBuilder;
	}
}
